import { ActionReducerMapBuilder, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { FieldType } from '@/view/Login/components/LoginForm/LoginForm';
import { userLoginAPI } from '@/api/userAPI';
import { getToken, setToken } from '@/utils/auth';

import { ResponseType } from '@/type/ResponseType';

type InitialState = {
  token: string,
}

const initialState: InitialState = {
  token: getToken() || '',
};

/**
 * @description 调用登录接口发送异步请求的回调函数
 * */
export const userLogin: any = createAsyncThunk('userLogin', async (formData: FieldType, { rejectWithValue }) => {
  try {
    return await userLoginAPI(formData);
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});


const userStore = createSlice({
  name: 'usersStore',
  initialState,
  reducers: {},
  extraReducers(builder: ActionReducerMapBuilder<InitialState>): void {
    builder.addCase(userLogin.fulfilled, (state: InitialState, action: PayloadAction<ResponseType<string>>): void => {
      const { payload }: { payload: ResponseType<string> } = action;
      state.token = payload.data;
      setToken(payload.data);
    });
  },
});


export default userStore.reducer;
